﻿using PLCSharp.Command;

namespace PLCSharp.FB.Sensor;

public class FB_Sensor
{
    /// <summary>
    /// 感应名称
    /// </summary>
    public string? strName { get; private set; }

    /// <summary>
    /// 感应信号
    /// </summary>
    public bool bSensor { get; private set; }

    /// <summary>
    /// 稳定时间
    /// </summary>
    public double tReady { get; private set; }

    /// <summary>
    ///  稳定计时器
    /// </summary>
    private readonly TON tonReady = new();

    /// <summary>
    /// On超时时间
    /// </summary>
    public double tOnOvertime { get; private set; }

    //On超时计时器
    private readonly TON tonOnOvertime = new();

    /// <summary>
    /// Off超时时间
    /// </summary>
    public double tOffOvertime { get; private set; }

    //Off超时计时器
    private readonly TON tonOffOvertime = new();

    public bool i_bOn { get; set; }

    public bool i_bOff { get; set; }
    public ST_SensorErr o_Err { get; set; } = new();

    /// <summary>
    /// 感应器的线号
    /// </summary>
    public string? i_strIO { get; set; }

    /// <summary>
    /// 块初始化
    /// </summary>
    private bool Init;

    /// <summary>
    /// 感应监测
    /// </summary>
    /// <param name="i_strName">感应名</param>
    /// <param name="i_tOnOverTime">应On超时</param>
    /// <param name="i_tOffOverTime">应Off超时</param>
    /// <param name="i_tReadyTime">防抖时间</param>
    /// <param name="i_bSensor">感应</param>
    public void FB(
        string? i_strName,
        double i_tOnOverTime,
        double i_tOffOverTime,
        double i_tReadyTime,
        bool i_bSensor)
    {
        //初始化
        if (!Init)
        {
            Init = true;
            strName = i_strName;
            o_Err.astrErr[0] = strName + "应ON超时 " + i_strIO;
            o_Err.astrErr[1] = strName + "应OFF超时 " + i_strIO;

            tOnOvertime = i_tOnOverTime;
            tOffOvertime = i_tOffOverTime;
            tReady = i_tReadyTime;
        }

        tonReady.FB(i_bSensor, tReady);
        bSensor = tonReady.Q;

        //超时

        tonOnOvertime.FB(i_bOn && !i_bSensor, tOnOvertime);

        o_Err.abErr[0] = tonOnOvertime.Q;

        tonOffOvertime.FB(i_bOff && i_bSensor, tOffOvertime);

        o_Err.abErr[1] = tonOffOvertime.Q;
    }
}